package com.zyfdroid.ambernicstartmenu.views;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.BatteryManager;
import android.util.AttributeSet;
import android.widget.TextView;
import com.zyfdroid.ambernicstartmenu.R;

public class BatteryPercentageView extends TextView {

    private BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            boolean charging = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED,0) != 0;
            int batteryPercentage = (int) ((level / (float) scale) * 100);
            setText(batteryPercentage + "% ");
            if(charging){
                setBatteryImage(R.drawable.batt_6);
            }
            else{
                if(batteryPercentage >= 90){
                    setBatteryImage(R.drawable.batt_1);
                } else if (batteryPercentage >= 65) {

                    setBatteryImage(R.drawable.batt_2);
                } else if (batteryPercentage >= 40) {

                    setBatteryImage(R.drawable.batt_3);
                } else if (batteryPercentage >= 15) {

                    setBatteryImage(R.drawable.batt_4);
                } else  {
                    setBatteryImage(R.drawable.batt_5);
                }

            }
        }
    };

    private void setBatteryImage(int resId){
        Drawable drawable = getResources().getDrawable(resId, getContext().getTheme());
        drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
        setCompoundDrawables(null,null,drawable,null);
    }

    public BatteryPercentageView(Context context) {
        super(context);
        init();
    }

    public BatteryPercentageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public BatteryPercentageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        // 注册电量变化广播接收器
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        getContext().registerReceiver(batteryReceiver, filter);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        // 解除注册电量变化广播接收器
        getContext().unregisterReceiver(batteryReceiver);
    }
}